<template>
  <div class="app-container">
    <div class="searchBox">
      <el-form :inline="true" :model="search" ref="searchForm">
        <el-form-item label="名称：" prop="name">
          <el-input v-model="search.name" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="编码：" prop="code">
          <el-input v-model="search.code" placeholder="请输入内容"></el-input>
        </el-form-item>
        <!-- <el-form-item label="状态：" prop="status">
          <el-select v-model="search.status">
            <el-option
              v-for="item in controlData.statusList"
              :key="item.key"
              :label="item.key"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item style="margin-top: -2px">
          <el-button type="primary" @click="searchQuery">查询</el-button>
          <el-button
            type="info"
            @click="
              search = {};
              searchQuery();
            "
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <qm-table
      ref="qmTable"
      :data="query"
      keyProp="formId"
      menuType="text"
      :formOptions="{ labelWidth: '120px' }"
      :menuOptions="{ width: 200 }"
      :rules="rules"
      :showView="false"
      :showOrder="false"
      :isCustomForm="true"
      formRefs="form1"
    >
      <qm-table-column field="name" sortable>名称</qm-table-column>
      <qm-table-column field="title" sortable>标题</qm-table-column>
      <qm-table-column field="code" sortable>编码</qm-table-column>
      <qm-table-column field="version" sortable>版本号</qm-table-column>
      <qm-table-column field="isCurrent" sortable fieldtype="enabledisable"
        >当前版本</qm-table-column
      >
      <qm-table-column field="isEnabled" sortable fieldtype="enabledisable"
        >是否启用</qm-table-column
      >

      <template #toolbar>
        <el-button @click="importForm" size="small" icon="el-icon-upload">
          导入
        </el-button>
        <el-button
          @click="exportForm"
          size="small"
          icon="el-icon-download"
          type="primary"
        >
          导出
        </el-button>
      </template>

      <template v-slot:moreBtn="{ row }">
        <el-button type="text" @click="design(row)">设计</el-button>
        <el-button type="text" @click="preview(row)">预览</el-button>
      </template>
      <template v-slot:form="{ models, controlData }">
        <el-form
          ref="form1"
          :model="models"
          label-width="120px"
          :rules="rules"
          label-suffix=":"
        >
          <div
            style="float: right;z-index: 2; position: relative;padding: 3px;"
          >
            <el-button
              v-if="'formTable' == tabActive"
              type="primary"
              @click="addTable()"
              icon="el-icon-plus"
              >选择数据源</el-button
            >
          </div>
          <el-tabs
            type="border-card"
            @tab-click="handleTabClick"
            v-model="tabActive"
          >
            <el-tab-pane label="基本配置" name="form">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="页面名称" prop="model.name">
                    <el-input v-model="models.model.name"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="页面编码" prop="model.code">
                    <el-input
                      v-model="models.model.code"
                      :disabled="pageAction != 'create'"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="版本号" prop="model.version">
                    <el-input v-model="models.model.version"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="模板页">
                    <el-select v-model="models.model.showType">
                      <el-option
                        v-for="item in controlData.showTypeOptions"
                        :key="item.key"
                        :label="item.key"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="是否当前版本">
                    <el-switch v-model="models.model.isCurrent"></el-switch>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否启用">
                    <el-switch v-model="models.model.isEnabled"></el-switch>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="是否启用工作流">
                    <el-switch
                      v-model="models.model.isEnableWorkflow"
                    ></el-switch>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="绑定流程">
                    <el-select v-model="models.model.defaultAppCode">
                      <el-option
                        v-for="item in controlData.workflowAppOptions"
                        :key="item.appCode"
                        :label="item.appName"
                        :value="item.appCode"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="是否是移动端">
                    <el-switch v-model="models.model.isMobile"></el-switch>
                  </el-form-item>
                </el-col>
                <el-col :span="12"></el-col>
              </el-row>-->
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="待办标题" prop="model.titleFormat">
                    <el-input v-model="models.model.titleFormat"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="代理类" prop="model.baseProxy">
                    <el-input v-model="models.model.baseProxy"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="数据源分配" name="formTable">
              <el-table :data="models.formTables" border style="width: 100%">
                <el-table-column
                  fixed
                  prop="name"
                  label="数据源名称"
                  width="150"
                ></el-table-column>
                <el-table-column
                  prop="code"
                  label="数据源编码"
                ></el-table-column>
                <el-table-column
                  prop="version"
                  label="版本"
                  width="60"
                ></el-table-column>
                <el-table-column prop="sort" label="保存顺序" width="160">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.sort"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="isCollection" label="是否集合">
                  <template slot-scope="scope">
                    <el-switch v-model="scope.row.isCollection"></el-switch>
                  </template>
                </el-table-column>
                <el-table-column prop="isReadOnly" label="是否只读">
                  <template slot-scope="scope">
                    <el-switch v-model="scope.row.isReadOnly"></el-switch>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="100">
                  <template slot-scope="scope">
                    <el-button @click="editTable(scope.row)" type="text"
                      >管理</el-button
                    >
                    <el-button
                      @click="removeTable(scope.row, models)"
                      type="text"
                      >移除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="调用示例" name="demo">
              <template v-if="!models.model.isEnableWorkflow">
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="列表页面">
                      <el-link type="primary"
                        >/smartform/hub/{{ models.model.code }}</el-link
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="新增页面">
                      <el-link type="primary"
                        >/smartform/hub/{{ models.model.code }}</el-link
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="编辑页面">
                      <el-link type="primary"
                        >/smartform/hub/{{ models.model.code }}?主键=?</el-link
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="查看页面">
                      <el-link type="primary"
                        >/smartform/view/{{ models.model.code }}?主键=?</el-link
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
              <template v-else>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="工作流新增页面">
                      <el-link type="primary"
                        >/smartform/workflow/{{ models.model.code }}</el-link
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="工作流编辑页面">
                      <el-link type="primary"
                        >/smartform/workflow/{{
                          models.model.code
                        }}?action=processEdit&taskId=任务ID&assigneeId=用户ID&appCode=工作流应用code</el-link
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="工作流查看页面">
                      <el-link type="primary"
                        >/smartform/workflow/{{
                          models.model.code
                        }}?action=processView&historyTaskId=任务ID&appCode=工作流应用code</el-link
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
            </el-tab-pane>
          </el-tabs>

          <vxe-modal
            v-model="tableModel.visible"
            :showFooter="true"
            fullscreen
            resize
            show-zoom
            width="1024px"
            destroy-on-close
          >
            <smart-table
              ref="smartTable"
              :models="tableModel.models"
              :controlData="tableModel.controlData"
            ></smart-table>

            <template #footer>
              <el-button
                type="primary"
                :loading="tableModel.saveLoading"
                @click="saveTable"
                >保 存</el-button
              >
            </template>
          </vxe-modal>
        </el-form>
      </template>
    </qm-table>

    <common-select
      v-model="commonSelectVisible"
      selectKey="selectSmartTable"
      selectMode="1"
      @success="doAddTable"
    ></common-select>

    <vxe-modal
      ref="xModal"
      v-model="publishVisible"
      width="800px"
      showFooter
      destroy-on-close
    >
      <smart-publish
        ref="publish"
        @done="publishVisible = false"
      ></smart-publish>

      <template #footer>
        <el-button @click="publish">上传</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
import Controller from "@/libs/framework/controller";
import CommonSelect from "@/views/commonSelect/list";
import SmartTable from "@/views/smartform/smartTable/create";
import SmartPublish from "@/views/smartform/smartVersion/create";
import _ from "lodash";
import request from "@/utils/request";
export default class Instance extends Controller {
  onBeforeInit() {
    this.urls = {
      model: "/smartform/smartForm/getListModel",
      query: "/smartform/smartForm/query",
      save: "/smartform/smartForm/save",
      delete: "/smartform/smartForm/delete",
      entity: "/smartform/smartForm/getEntity"
    };
  }

  mixin() {
    return {
      components: {
        CommonSelect,
        SmartTable,
        SmartPublish
      },
      data() {
        return {
          commonSelectVisible: false,
          tabActive: "form",
          rules: {
            "model.name": [
              { required: true, message: "请输入页面名称", trigger: "blur" }
            ],
            "model.code": [
              { required: true, message: "请输入页面编码", trigger: "blur" }
            ],
            "model.version": [
              { required: true, message: "请输入版本号", trigger: "blur" }
            ]
          },
          tableModel: {
            visible: false,
            models: {},
            controlData: {},
            saveLoading: false
          },
          publishVisible: false
        };
      },
      methods: {
        design(form) {
          window.open(`/design.html#/zh-CN/?formId=${form.formId}`);
        },
        preview(form) {
          // let url = `/smartform/render?pageId=${form.formId}&pageCode=${
          //   form.code
          // }&_r=${new Date().getTime()}`;

          let url = `/smartform/hub/${form.code}`;
          if (form.isEnableWorkflow) {
            url = `/smartform/workflow/${form.code}`;
          }
          // this.$router.push({ path: '/smartform/render', query: { pageId: form.formId, pageCode: form.code } });
          window.open(url);
        },
        addTable() {
          this.commonSelectVisible = true;
        },
        doAddTable(result) {
          let vm = this.$refs["qmTable"].viewModel;
          let formTables = vm.models.formTables;
          if (result && result.length > 0) {
            let count = formTables.length + 1;
            _.each(result, (table, index) => {
              if (
                _.findIndex(formTables, {
                  tableId: table.tableId
                }) == -1
              ) {
                formTables.push(
                  _.extend({}, vm.defaults.formTable, {
                    tableId: table.tableId,
                    name: table.name,
                    code: table.code,
                    version: table.version,
                    sort: count,
                    isCollection: false,
                    isReadOnly: false
                  })
                );
                count++;
              }
            });
          }
          this.commonSelectVisible = false;
        },
        editTable(table) {
          let loading = this.notifyInfo("数据加载中...");
          request({
            url: "/smartform/smartTable/getEntity",
            method: "post",
            data: { pageAction: "edit", tableId: table.tableId }
          }).then(vm => {
            this.tableModel.models = vm.models;
            this.tableModel.controlData = vm.controlData;
            this.tableModel.visible = true;
            loading.close();
          });
        },
        saveTable() {
          this.$refs["smartTable"].$refs["form1"].validate().then(v => {
            if (v) {
              this.tableModel.saveLoading = true;
              let postModel = _.extend({}, this.tableModel.models);
              postModel.pageAction = "edit";
              postModel.tableId = postModel.model.tableId;
              request({
                url: "/smartform/smartTable/save",
                method: "post",
                data: postModel
              }).then(r => {
                if (r && r.success) {
                  this.tableModel.saveLoading = false;
                  this.tableModel.visible = false;
                  this.notifySuccess("保存成功");
                } else {
                  this.notifyError(r.message || "保存失败");
                }
              });
            }
          });
        },
        removeTable(table, models) {
          models.formTables.remove(table);
        },
        handleTabClick(tab, event) {
          this.tabActive = tab.name;
        },

        exportForm() {
          let formIds = this.$refs["qmTable"].getSelectedRows();

          if (!formIds || formIds.length == 0) {
            this.msgError("请至少勾选一条记录");
            return;
          }
          let ids = [];
          formIds.forEach(form => {
            ids.push(form.formId);
          });
          window.open(
            `${
              process.env.VUE_APP_BASE_API
            }/smartform/smartVersion/export?formIds=${ids.join(
              ","
            )}&_r=${Math.random()}`
          );
        },

        importForm() {
          // window.$.open("/smartform/smartVersion/create", () => {
          //   this.searchQuery();
          // });
          this.publishVisible = true;
        },

        publish() {
          this.$refs["publish"].upload();
        }
      },
      mounted() {}
    };
  }
}
</script>

<style scoped lang="scss"></style>
